package com.zksy.pcr;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.zksy.pcr.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @program: pcr-server
 * @author: isam2016
 * @create: 2025-07-04 09:43
 **/
@RestController
@Slf4j
@RequestMapping("/api/emb")
public class PcrController {

    /**
     * 兼容老版
     * pcr文件存储上传
     * @param files
     * @return
     */
    @PostMapping(value = "/upLoadFile")
    public Object upLoadFile(@RequestParam("files") MultipartFile[] files,
                             @RequestParam("pid") String pid,
                             @RequestParam("time") Long time,
                             @RequestParam("nonceStr") String nonceStr,
                             @RequestParam("params") String params) {
        Object response = null;
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString();
        try {
            log.info("PCR读取文件 pid:[{}]  time:[{}] nonceStr:[{}]UUID:[{}]", pid, time, nonceStr, uuidStr);
            if(pid == null || time== null || nonceStr == null || params == null || files.length < 1 ){
                return new ObjectRestResponse<>().msg("缺少数据").rel(Response.FAILURE);
            }
            HashMap<String, String> fileInfo = new HashMap<>();
            // 文件MD5 校验  客户可自行决定是否进行文件校验
            FileMd5s fileMd5  = JSON.parseObject(params, FileMd5s.class);
            List<FileMd5> fileMd5List = fileMd5.getFileMd5List();
            if( fileMd5List.size() <1 || files.length != fileMd5List.size()){
                return new ObjectRestResponse().rel(Response.FAILURE).msg("文件没有MD5值，或文件数量和MD5数量不一致").code(109);
            }
            // 校验文件的md5值
            for (FileMd5 currentInfo : fileMd5List) {
                String currentFileName = currentInfo.getFilename();
                String currentMd5 = currentInfo.getFilemd5();
                fileInfo.put(currentFileName, currentMd5);
            }
            for (MultipartFile file : files) {
                File currentFile = HttpClientUtil.multipartFileToFile(file);
                if(currentFile == null){
                    throw new RuntimeException("文件内容为空");
                }
                String currentFileMd5 = SecureUtil.md5(currentFile);
                String fileInfoMd5 = fileInfo.get(file.getOriginalFilename());
                if( StringUtils.isEmpty(fileInfoMd5) || !fileInfoMd5.equals(currentFileMd5)){
                    throw new RuntimeException("文件MD5校验错误");
                }
            }
            // 文件校验md5 结束

            // 开始进行文件过滤
            PcrData pcrData = null;
            for (MultipartFile multipartFile : files) {
                if(multipartFile.getOriginalFilename().equals("channeldata.json")){
                    StringBuffer sb = new StringBuffer();
                    try {
                        File file = HttpClientUtil.multipartFileToFile(multipartFile);
                        FileReader fileReader = new FileReader(file);
                        Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
                        int ch = 0;
                        while ((ch = reader.read()) != -1) {
                            sb.append((char) ch);
                        }
                        fileReader.close();
                        reader.close();
                    }catch (Exception e){
                        e.printStackTrace();
                        throw new RuntimeException(e.getMessage());
                    }
                    String line = sb.toString().replaceAll("\r\n", "").replaceAll(" ", "");
                    pcrData  = JSON.parseObject(line, PcrData.class);
                    // 进行业务处理
                }
            }
            response = new ObjectRestResponse().rel(Response.SUCCESS).msg("数据").code(1);
        }  catch (Exception e) {
            e.printStackTrace();
            log.error("更新pcr实验数据链接失败 ! 异常信息 : [{}]", e);
            response = new ObjectRestResponse().rel(Response.FAILURE).msg(e.getMessage()).code(-2);
        }
        return  response;
    }
}
